<template>

	<view class="confirmOrder pb-200">
		<Navigation title="确认订单" background="#fff" />
		<view class="pv-32 ph-40 address" @click="toAddress">
			<view class="mt-25" v-if="addressData">
				<view class="f ai-c jc-s-b">
					<view class="f ai-c">
						<view class="w-104 h-32 b-4 default f ai-c jc-c fs-22 text-color5 mr-16"
							v-show="addressData.defaultStatus">
							默认地址
						</view>
						<view class="fs-28 fw-500 text-color4">{{ addressData.name }}
							{{ phoneNumbe(addressData.mobile) }}
						</view>
					</view>
					<image src="http://cwht.ricecs.cn/app/shop/edit.png" class="w-32 h-32"></image>
				</view>
				<view class="fs-24 text-color3 mt-16">地址：{{ addressData.areaName }}{{ addressData.detailAddress }}
				</view>
			</view>
			<view v-else class="mt-32 fs-28 fw-500 text-color3">请选择地址~</view>
		</view>
		<template v-if="params.combinationActivityId">
			<view class="mt-20 background-white b-24 ph-32 pv-32" v-for="(item, index) in list" :key="index">
				<view class="ml-8 fs-28 fw-600 text-color4">{{ item.shop }}</view>
				<view class="f ai-c mt-33" v-for="(items, indexs) in item.goods" :key="indexs">
					<image :src="items.spu.picUrl[0]" v-if="items.spu.picUrl" class="w-160 h-160 b-12 mr-32"></image>
					<view class="f fd-c f1">
						<view class="fs-32 fw-600 text-color4">{{ items.spu.name }}</view>
						<view class="mt-12">
							<text class="fs-22 text-color8">¥</text>
							<!-- <text class="fs-36 fw-600 text-color8">{{ items.sku.combinationPrice / 100 }}</text> -->
							<text class="fs-36 fw-600 text-color8">{{ formater(items.sku.combinationPrice) }}</text>
						</view>

					</view>
				</view>
			</view>
		</template>
    <template v-else-if="params.seckillActivityId">
			<view class="mt-20 background-white b-24 ph-32 pv-32" v-for="(item, index) in list" :key="index" >
			  <view class="ml-8 fs-28 fw-600 text-color4">{{ item.shop }}</view>
			  <view class="f ai-c mt-33" v-for="(items, indexs) in item.goods" :key="indexs">
			    <image :src="items.spu.picUrl[0]" v-if="items.spu.picUrl" class="w-160 h-160 b-12 mr-32"></image>
			    <view class="f fd-c f1">
			      <view class="fs-32 fw-600 text-color4">{{ items.spu.name }}</view>
			      <view class="mt-12">
			        <text class="fs-22 text-color8">¥</text>
			        <text class="fs-36 fw-600 text-color8">{{formater(orderData.price.payPrice) }}</text>
			      </view>


					</view>
				</view>
			</view>
		</template>
		<template v-else>
			<view class="mt-20 background-white b-24 ph-32 pv-32" v-for="(item, index) in list" :key="index">

				<view class="ml-8 fs-28 fw-600 text-color4">{{ item.shop }}</view>
				<view class="f ai-c mt-33" v-for="(items, indexs) in item.goods" :key="indexs">
					<image :src="items.sku.picUrl" class="w-160 h-160 b-12 mr-32"></image>
					<view class="f fd-c f1">
						<view class="fs-32 fw-600 text-color4">{{ items.spu.name }}</view>
						<view class="mt-12">
							<text class="fs-22 text-color8">¥</text>
							<text class="fs-36 fw-600 text-color8">{{ formater(items.sku.price) }}</text>
						</view>
						<view class="f ai-c jc-f-e">
							<u-number-box v-model="items.count" :min="1" :max="items.sku.stock"
								:disablePlus="items.count == items.sku.stock" :disableMinus="items.count == 1" integer
								:disabledInput="items.count >= items.sku.stock"
								@change="getOrdersettlement"></u-number-box>
						</view>
					</view>
				</view>
			</view>
		</template>

		<view class="background-white mt-20 pv-32 ph-32 b-24">
			<view class="f ai-c jc-s-b mb-32">
				<view class="fs-26 text-color3">商品金额</view>
				<view class="f ai-c">
					<view class="fs-26 fw-600 text-color4 mr-40">¥{{ formater(orderData.price.totalPrice) }}</view>
					<u-icon name="arrow-right" color="#D8D8D8" size="10"></u-icon>
				</view>
			</view>
			<view class="f ai-c jc-s-b mb-32" @click="toCoupon"
				v-if="!params.combinationActivityId && !params.seckillActivityId ">
				<view class="fs-26 text-color3">优惠券</view>
				<view class="f ai-c">
					<view class="fs-26 text-color4 mr-40" v-if="couponData">
						<view v-if="couponData.discountType == 1">满{{formater(couponData.usePrice)}}减{{formater(couponData.discountPrice)}} </view>
						<view v-if="couponData.discountType == 2">{{ couponData.discountPercent }}折</view>
					</view>
					<view class="fs-26 text-color4 mr-40" v-else> 请选择</view>
					<u-icon name="arrow-right" color="#D8D8D8" size="10"></u-icon>
				</view>
			</view>
			<view class="f ai-c jc-s-b mb-32">
				<view class="fs-26 text-color3">支付方式</view>
				<view class="f ai-c">
					<view class="fs-26 text-color4 mr-40">微信支付</view>
					<u-icon name="arrow-right" color="#D8D8D8" size="10"></u-icon>
				</view>
			</view>
			<view class="f ai-c jc-s-b">
				<view class="fs-26 text-color3">运费</view>
				<view class="f ai-c">
					<view class="fs-26 fw-600 text-color4 mr-60">¥ {{formater(orderData.price.deliveryPrice)}}</view>
				</view>
			</view>
		</view>
		<view class="background-white b-24 ph-32 h-100 mt-20 f ai-c jc-s-b"
			v-if="!params.combinationActivityId && !params.seckillActivityId">
			<view class="fs-26">
				<text class="text-color3">拥有积分</text>
				<text class="text-color4">({{ orderData.totalPoint || 0 }}) ， 可抵扣</text>
				<text class="text-color8 fw-600">{{ orderData.price.pointPrice}}</text>
				<text class="text-color4">元</text>
			</view>
			<image :src="params.pointStatus ? selectCheck : select" class="w-32 h-32" @click="changePoint"></image>
		</view>
		<view class="background-white b-24 ph-32 h-100 mt-20 f ai-c jc-s-b">
			<view class="fs-28 text-color4 mr-32">订单备注</view>
			<view class="f f1 fs-28">
				<u--input placeholder="告诉商家您的其他需求" v-model="params.remark" fontSize="28rpx" border="none"></u--input>
			</view>
		</view>
		<view class="f ai-c jc-s-b bot h-160 w-f pl-32 pr-40" :style="{ paddingBottom: safeAreaBottom + 'px' }">
			<view>
				<text class="fs-22 text-color8">¥</text>
				<!-- <text class="fs-36 fw-600 text-color8">{{ orderData.price.payPrice / 100 }}</text> -->
				<text class="fs-36 fw-600 text-color8">{{ formater(orderData.price.payPrice) }}</text>
			</view>
			<view class="w-200 h-80 b-80 fs-28 fw-500 text-color5 btn f ai-c jc-c" @click="toConfirmOrder">去结算</view>
		</view>
	</view>
	<!-- 优惠券 -->
	<Coupon ref="coupon" :list="list" :orderData="orderData" :params="params" @selectCoupon="selectCoupon" />

</template>
<script setup lang="ts">
	import { ref, computed } from 'vue';
	import { onShow, onLoad } from '@dcloudio/uni-app';
	import { useAuthStore } from '@/store/modules/auth';
	import { phoneNumbe,formater } from '@/utils/global';
	import { addressGetDefault } from '@/services/api/address';
	import { orderCreate, orderSubmit, ordersettlement } from '@/services/api/shop/order';
	import selectCheck from '@/static/select-check.png';
	import select from '@/static/select.png';
	import Coupon from './Coupon.vue';
	import { socialUser } from "@/services/api/index";

	const authStore = useAuthStore();
	const addressData = ref<any>({});
	const coupon = ref();
	const couponData = ref();
	const openid = ref();
	const list = ref<any[]>([]);
	const params = ref<any>({
		items: [],
		pointStatus: false,
		//1, "快递发货" 2, "用户自提"
		deliveryType: 1,
		addressId: null,
		couponId: null,
		remark: '',
		combinationActivityId: '',
		combinationHeadId: '',
		seckillActivityId: '',
	});
	const orderData = ref<any>(0);
	const couponList = ref([]);

	onLoad((opt : any) => {
		if (opt.combinationActivityId) {
			params.value.combinationActivityId = opt.combinationActivityId
			params.value.combinationHeadId = opt.combinationHeadId
		}
		if (opt.seckillActivityId) {
			params.value.seckillActivityId = opt.seckillActivityId
		}
	})
	onShow(() => {
		let pages = getCurrentPages();
		let currPage : any = pages[pages.length - 1];
		let addressDatas = currPage.data.addressData;

		//选择地址
		if (addressDatas) {
			addressData.value = addressDatas;
			params.value.addressId = addressData.value.id;
		} else {
			getDefaultAddress();
		}
		list.value = authStore.getOrderGoods;
		getOrdersettlement();
		if (!authStore.getOpenId) {
			uni.login({
				provider: 'weixin',
				success: async (res) => {
					let result = await socialUser({ userID: authStore.getUserId, type: 10, state: '123', code: res.code });
					openid.value = result.data.openid
				},
			})
		}
	});

	//是否使用积分
	function changePoint() {
		params.value.pointStatus = !params.value.pointStatus;
		getOrdersettlement();
	}

	//选择的优惠券
	async function selectCoupon(data : any) {
		couponData.value = data;
		params.value.couponId = data.id;
		getOrdersettlement();
	}

	//获取结算信息
	async function getOrdersettlement() {
		const itemsData : any = [];
		if (params.value.combinationActivityId || params.value.seckillActivityId) {
			list.value.forEach((item) => {
				item.goods.forEach((items : any) => {
					itemsData.push({
						skuId: items.sku.skuId,
						count: items.count,
					});
				});
			});
		} else {
			list.value.forEach((item) => {
				item.goods.forEach((items : any) => {
					itemsData.push({
						skuId: items.sku.id,
						count: items.count,
					});
				});
			});
		}

		console.log({
			items: itemsData,
			addressId: addressData.value.id || null,
			pointStatus: params.value.pointStatus,
			deliveryType: params.value.deliveryType,
			couponId: params.value.couponId,
			combinationActivityId: params.value.combinationActivityId,
			combinationHeadId: params.value.combinationHeadId
		})
		const { data } = await ordersettlement({
			items: itemsData,
			addressId: addressData.value.id || null,
			pointStatus: params.value.pointStatus,
			deliveryType: params.value.deliveryType,
			couponId: params.value.couponId,
			seckillActivityId: params.value.seckillActivityId,
			combinationActivityId: params.value.combinationActivityId,
			combinationHeadId: params.value.combinationHeadId
		});

		orderData.value = data;
		// getCoupon();
	}

	//结算
	async function toConfirmOrder() {
		if (!addressData.value) {
			uni.showToast({
				title: '请选择地址',
				icon: 'none',
			});
			return;
		}

		params.value.items = [];

		if (params.value.combinationActivityId || params.value.seckillActivityId) {
			list.value.forEach((item) => {
				item.goods.forEach((items : any) => {
					params.value.items.push({
						skuId: items.sku.skuId,
						count: items.count,
					});
				});
			});
		} else {
			list.value.forEach((item) => {
				item.goods.forEach((items : any) => {
					params.value.items.push({
						skuId: items.sku.id,
						count: items.count,
					});
				});
			});
		}
		params.value.terminal = 10;
		const { data } = await orderCreate(params.value);
		pay(data);
	}

	//调起支付
	async function pay(data : any) {
		let result = await orderSubmit({
			id: data.payOrderId,
			channelCode: 'wx_lite',
			channelExtras: { openid: authStore.getOpenId ? authStore.getOpenId : openid.value }
		});
		let displayContent = JSON.parse(result.data.displayContent);
		await uni.requestPayment({
			provider: "wxpay",
			timeStamp: displayContent.timeStamp,
			nonceStr: displayContent.nonceStr,
			package: displayContent.packageValue,
			signType: displayContent.signType,
			paySign: displayContent.paySign,
			success(res2) {
				uni.showToast({
					title: '支付成功',
				});
				setTimeout(() => {
					uni.redirectTo({
						url: '/pages_mine/order'
					})
				}, 1000);

			},
			fail(e) {
				uni.showToast({
					title: '支付失败,请重新支付',
					icon: 'none'
				})
				setTimeout(() => {
					uni.redirectTo({
						url: '/pages_mine/order'
					})
				}, 1000);
			}
		})
	}

	const toCoupon = () => {
		coupon.value.getShow(true);
	};

	//获取默认地址
	async function getDefaultAddress() {
		const { data } = await addressGetDefault({});
		addressData.value = data;
		params.value.addressId = addressData.value.id;
	}

	//跳转地址
	function toAddress() {
		uni.navigateTo({
			url: `/pages_mine/myAddress?type=select`,
		});
	}

	//底部安全距离
	const systemInfo = uni.getSystemInfoSync();
	let safeArea = systemInfo.safeArea;
	let screenHeight = systemInfo.screenHeight;
	let safeAreaBottom = screenHeight - safeArea.bottom;
</script>
<style lang="scss" scoped>
	.confirmOrder {
		background: #f2f2f2;
		min-height: 100vh;

		.bot {
			position: fixed;
			left: 0;
			bottom: 0;
			background: #fff;
			z-index: 111;

			.btn {
				background: #fabb3c;
			}
		}

		::v-deep.u-number-box__plus {
			background: #fff !important;
			width: 40rpx !important;
		}

		::v-deep .u-number-box__minus {
			background: #fff !important;
			width: 40rpx !important;
		}

		::v-deep .u-icon__icon {
			font-size: 20rpx !important;
		}

		::v-deep .u-number-box__input {
			width: 80rpx !important;
			height: 40rpx !important;
			background: #f4f4f4 !important;
			border-radius: 4rpx !important;
			font-family: PingFangSC-Medium;
			font-weight: 500 !important;
			font-size: 24rpx !important;
			color: #1a1a1a !important;
		}

		.background-white {
			background: #fff;
		}

		.address {
			background: #fff;
			border-radius: 0 0 24rpx 24rpx;
		}

		.default {
			background: #f54040;
		}
	}
</style>